package com.dimld.connect;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class ConnectContainer {
    private static final Logger                                log       = LoggerFactory.getLogger(ConnectContainer.class);
    private static final ConcurrentHashMap<String, ConnectorI> container = new ConcurrentHashMap<>();

    public static void put(ConnectorI conn) {
        log.info("添加连接[" + conn.getUuid() + "]类型[" + conn.getConnType() + "]");
        container.put(conn.getUuid(), conn);
        log.info("当前连接数量[" + container.size() + "]");
    }

    /**
     * 从容器中移除指定连接
     *
     * @param uuid
     * @return
     */
    public static ConnectorI remove(String uuid) {
        ConnectorI conn = container.remove(uuid);
        if(conn != null)
            log.info("移除连接[{}]类型[{}]，剩余连接数量[{}]", uuid, conn.getConnType(), container.size());
        return conn;
    }

    /**
     * 根据UUID获取指定连接
     *
     * @param uuid
     * @return
     */
    public static ConnectorI get(String uuid) {
        ConnectorI connectorI = container.get(uuid);
        return connectorI;
    }

    /**
     * 获取所有连接
     *
     * @return
     */
    public static ConcurrentHashMap<String, ConnectorI> getAllConnect() {
        return container;
    }

    public static List<ConnectorI> getConnector4ClusterMember(String uuid) {
        List<ConnectorI> list = new ArrayList<>();
        for (ConnectorI connectorI : container.values()) {
            if (connectorI != null && connectorI.getBindServiceUuid() != null && connectorI.getBindServiceUuid().equals(uuid)) {
                list.add(connectorI);
            }
        }
        return list;
    }
}
